//
//  ZWLGameView.swift
//  ZWLDY
//
//  Created by zwl on 2016/10/4.
//  Copyright © 2016年 zwl. All rights reserved.
//

import UIKit

private let gameViewCellID = "GameViewCellID"
private let contentInsetTop : CGFloat = 10

class ZWLGameView: UIView {

    @IBOutlet weak var collectionView: UICollectionView!
    
    var groups : [AnchorGroup]? {
        didSet {
            // 1.移除前两组数据
            groups?.removeFirst()
            groups?.removeFirst()
            
            // 2.添加更多组
            let moreGroup = AnchorGroup()
            moreGroup.tag_name = "更多"
            groups?.append(moreGroup)
            
            // 2.刷新表格
            collectionView.reloadData()
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: gameViewCellID)
        collectionView.contentInset = UIEdgeInsets(top: 0, left: contentInsetTop, bottom: 0, right: contentInsetTop)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: 80, height: 90)
        
    }
  

}

extension ZWLGameView {
    class func gameView() -> ZWLGameView {
        return Bundle.main.loadNibNamed("ZWLGameView", owner: nil, options: nil)?.last as! ZWLGameView
    }
}

// MARK:- 数据源方法
extension ZWLGameView : UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return groups?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell  = collectionView.dequeueReusableCell(withReuseIdentifier: gameViewCellID, for: indexPath) as! CollectionGameCell
        cell.group = groups![indexPath.item]
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath.item)
    }
}
